# -*- coding: utf-8 -*-

import json
from django.core import serializers

from django.contrib.auth.models import User, Permission

from django.test import TestCase
from django.test.client import Client

from student.models import Student

class SearchTest(TestCase):
  fixtures = ['students.json']
  
  def setUp(self):
    can_vote_permission = Permission.objects.get(codename = 'can_search', content_type__name = u'student')
    
    # Set up a super user
    user = User.objects.create_user('test_superuser', '', '123')
    user.user_permissions.add(can_vote_permission)
    user.save()
  
  def test_search_exact_emso(self):
    """Exact EMSO search, should return only one student
    """
    
    self.client.login(username = 'test_superuser', password = '123')
    response = self.client.post('/student/search/', {'query': '63110179'}, HTTP_X_REQUESTED_WITH = 'XMLHttpRequest')
    
    students = json.loads(response.content)
    self.failUnlessEqual(len(students), 1)
    self.failUnlessEqual(students[0]['fields']['user']['fields']['first_name'], u'Mihael')
  
  def test_search_emso(self):
    """Should return all students who's emso begins with a specific digits
    """
    self.client.login(username = 'test_superuser', password = '123')
    response = self.client.post('/student/search/', {'query': '631101'}, HTTP_X_REQUESTED_WITH = 'XMLHttpRequest')
    
    students = json.loads(response.content)
    for student in students:
      self.failUnlessEqual(student['pk'][:6], '631101')
  
  def test_search_first_name(self):
    """Should find all students who's first names starts with the specified query
    """
    self.client.login(username = 'test_superuser', password = '123')
    response = self.client.post('/student/search/', {'query': 'Mih'}, HTTP_X_REQUESTED_WITH = 'XMLHttpRequest')
    
    students = json.loads(response.content)
    for student in students:
      self.failUnlessEqual(student['fields']['user']['fields']['first_name'][:3], 'Mih')
  
  def test_search_first_last_names(self):
    """Should find all students who's first and last names starts with the specified query
    """
    self.client.login(username = 'test_superuser', password = '123')
    response = self.client.post('/student/search/', {'query': 'Mih Za'}, HTTP_X_REQUESTED_WITH = 'XMLHttpRequest')
    
    students = json.loads(response.content)
    for student in students:
      self.failUnlessEqual(student['fields']['user']['fields']['first_name'][:3], 'Mih')
      self.failUnlessEqual(student['fields']['user']['fields']['last_name'][:2], 'Za')
